<?php

class BrandManageController extends Controller
{

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(

            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('add','publish','search','getlist','getbyid','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		);
	}

    public function actionAdd()
    {
        $brandSearch = Brand::model()->findByAttributes(array('name_en'=>$_POST['name_en']));

        $brand = new Brand();
        if(!empty($_POST['id']))$brand = Brand::model()->findByPk(new MongoId($_POST['id']));

        if(!empty($_POST['id']))
        {
            if($brand->name_en != $_POST['name_en'] && !empty($brandSearch))
            {
                header("HTTP/1.0 400 brand is exist");
                die();
            }
        }else if(!empty($brandSearch)){
                header("HTTP/1.0 400 brand is exist");
                die();
        }
        $brand->name_zn = $_POST["name_zn"];
        $brand->name_en = $_POST["name_en"];
        $brand->desc_en = $_POST["desc_en"];
        $brand->desc_zn = $_POST["desc_zn"];
        $brand->thumb = $_POST["thumb"];
        $brand->image = $_POST["rel_image"];
        $brand->website = $_POST["website"];
        $brand->status = 1;
        $brand->published = false;
        empty($_POST['id'])?$brand->operation = INSERT:$brand->operation= UPDATE;
        
        $brand->save(false);
    }

    public function actionPublish()
    {
        $query = array(
            'conditions' => array(
                'published'=> array('==' =>false , ),
               // 'channel'=>array('=='=>constant("channel_homepage"))
            ),
        );

        $result = Brand::model()->findAll($query);
        $category = Category::model()->findAll($query);
        if(count($result) == 0 && count($category)==0)
        {
            $this->redirect("/tao/brand.html");
            return;
        }

        $version = Version::model()->find();
        $version->versionNo = $version->versionNo + 1;
        $file_zn = fopen(_VERSION_DATAPAK_PATH_ZN."{$version->versionNo}_version.txt", "x");
        $file_en = fopen(_VERSION_DATAPAK_PATH_EN."{$version->versionNo}_version.txt", "x");
        foreach ($result as $key => $value) {
            

            $value->_id = (string)$value->_id;

            if($value->operation == DELETE)
            {
                fwrite($file_zn,"delete from brand where id='{$value->_id}';\n");
                fwrite($file_en,"delete from brand where id='{$value->_id}';\n");
            }else{
                if($value->operation == UPDATE)
                {
                    fwrite($file_zn,"delete from brand where id='{$value->_id}';\n");
                    fwrite($file_en,"delete from brand where id='{$value->_id}';\n");
                }
                fwrite($file_zn, "INSERT INTO 'brand' ( 'name','desc','icon','image','website','id' ) VALUES ( '{$value->name_zn}','{$value->desc_zn}','{$value->thumb}','{$value->image}','{$value->website}','{$value->_id}' );\n");    
                fwrite($file_en, "INSERT INTO 'brand' ( 'name','desc','icon','image','website','id' ) VALUES ( '{$value->name_en}','{$value->desc_en}','{$value->thumb}','{$value->image}','{$value->website}','{$value->_id}' );\n");    
            }

            $value->_id = new MongoId($value->_id);
            // $value->status>0? $value->version = $version->versionNo:$value->version = -1;
            $value->published = true;
            $value->save(false);
            
        }

        foreach ($category as $key => $value) {

            $value->_id = (string)$value->_id;

            if($value->operation == DELETE)
            {
                fwrite($file_zn,"delete from category where id='{$value->_id}';\n");
                fwrite($file_en,"delete from category where id='{$value->_id}';\n");
            }else{
                if($value->operation == UPDATE)
                {
                    fwrite($file_zn,"delete from category where id='{$value->_id}';\n");
                    fwrite($file_en,"delete from category where id='{$value->_id}';\n");
                }
                fwrite($file_zn, "INSERT INTO 'category' ( 'name','desc','code','icon','parentId','id' ) VALUES ( '{$value->name_zn}','{$value->desc_zn}',{$value->code},'{$value->icon}','{$value->parentId}','{$value->_id}' );\n");    
                fwrite($file_en, "INSERT INTO 'category' ( 'name','desc','code','icon','parentId','id' ) VALUES ( '{$value->name_en}','{$value->desc_en}','{$value->code}','{$value->icon}','{$value->parentId}','{$value->_id}' );\n");    
            }

            $value->_id = new MongoId($value->_id);
            $value->published = true;
            $value->save(false);
        }


        $version->save(false);
        fclose($file_zn);
        fclose($file_en);

        $this->redirect("/tao/brand.html");
    } 

    /**
     * 获得版本信息
     */
    public function actionGetList($iDisplayStart=0,$iDisplayLength=10,$search_name='')
    {
        $resultColumn = array('name_zn','name_en','thumb');
        $query = array(
            'conditions' => array(
                'status'=> array('>' =>0 , ),
                'name_zn'=>array('=='=>new MongoRegex("/^{$search_name}/i"))
               // 'channel'=>array('=='=>constant("channel_homepage"))
            ),
            'select'=>$resultColumn,
            'limit'=>$iDisplayLength,
            'offset'=>$iDisplayStart,
        );

        $result = Brand::model()->findAll($query);

      
        $records = array();
        $records["aaData"] = array(); 

        if(!empty($result))
            foreach ($result as $key => $value) {
            $tmp = array();
            $value->_id = (string)$value->_id;
            foreach ($value as $key1=>$value1) {
                if(in_array($key1, $resultColumn))
                {
                    if($key1=='thumb')
                        array_push($tmp, "<img src='/dubai/{$value1}' class='img-thumnail' style='max-height:100px' alrt=''>");
                    else
                        array_push($tmp, $value1);
                }
            }
            array_push($tmp, '<a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs blue btn-editable"><i class="fa fa-pencil"></i> Edit</a> <a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs red btn-removable"><i class="fa fa-times"></i> Delete</a>  ');
            array_push($records["aaData"], $tmp);
        }

        $records["iTotalRecords"] = Brand::model()->count($query);
        $records["iTotalDisplayRecords"] = Brand::model()->count($query);
  
        echo json_encode($records);
    }

    public function actionSearch($name)
    {
        $resultColumn = array('name_en','_id');
        $query = array(
            'conditions' => array(
                'status' => array('>'=>0),
                'name_en'=>array('=='=>new MongoRegex("/^{$name}/i"))
            ),
            'select'=>$resultColumn,
        );

        $result = Brand::model()->findAll($query);
        $records = array();
        if(!empty($result))
        {
            foreach ($result as $key => $value) {
                $value->_id = (string)$value->_id;
                foreach ($value as $key1=>$value1) {
                    if(!in_array($key1, $resultColumn))
                    {
                        unset($value[$key1]);
                    }
                }

                $obj['id'] = $value->_id;
                $obj['text'] = $value->name_en;
                array_push($records, $obj);
            }
        }



        echoStringToMobile(json_encode(array("results"=>$records)));

    }

    public function actionGetById($id)
    {
        $brand = Brand::model()->findByPk(new MongoId($id));
        $brand->_id = (string)$brand->_id;
        echoStringToMobile(json_encode($brand));
    }

    public function actionDelete($id)
    {
        $query = array(
            'conditions' => array(
                'brand' => array('=='=>$id),
                'status' => array('>'=>0),
            ),
        );

        $result = Goods::model()->count($query);
        if($result>0)
        {
            header("HTTP/1.0 400 Bad Request");
            die();
        }else{
            $category = Brand::model()->findByPk(new MongoId($id));
            $category->status = -1;
            $category->published = false;
            $category->operation = DELETE;
            $category->save(false);
        }

    }
}